<template>
  <header class="breadcrumb" v-if='!$route.meta.noBreadcrumb'>
    <el-breadcrumb separator="/" >
      <el-breadcrumb-item :to="item"  v-for="item in breadcrumbList" :key="item.path">{{item.title}}</el-breadcrumb-item>
    </el-breadcrumb>
  </header>
</template>
<script lang="ts">
import { useRoute } from 'vue-router'
import { defineComponent, ref, watch } from 'vue'

export default defineComponent({
  setup() {
    const currentRoute = useRoute()
    const breadcrumbList = ref([])
    // 监听路由的变化
    watch(() => currentRoute.path,()=>{
      const filterArr: any[] = currentRoute.matched.filter(item => item.name); // 先过滤掉没有name的路由
      const mapstring: string = sessionStorage.getItem('breadcrumb') || ''
      if(mapstring || mapstring !== '') {
        let sessionStorageArr: any[] = JSON.parse(mapstring)
        if(sessionStorageArr.length === filterArr.length) {  // 获取到的路由长度等于本地存储的路由长度
          sessionStorageArr.forEach((item, index) => {
            if(filterArr[index].path !== item.path && filterArr[index].meta.hidden) {
              sessionStorageArr.push(filterArr[index])
            }else {
              sessionStorageArr[index] = filterArr[index]
            }
          })
        }else if(sessionStorageArr.length < filterArr.length){ // 获取到的路由长度小于本地存储的路由长度
          sessionStorageArr = filterArr
        }else {
          if(sessionStorageArr[sessionStorageArr.length-1].path !== filterArr[filterArr.length-1].path) {
            sessionStorageArr = filterArr
          }
        }
        const arr1:any = []
        sessionStorageArr.forEach(element => {
          let obj = {
            path: element.path,
            name: element.name,
            title: element.title || element.meta.title,
          }
          arr1.push(obj)
        });
        sessionStorage.setItem('breadcrumb', JSON.stringify(arr1))
      }else {
        const arr:any = []
        filterArr.forEach(element => {
          let obj = {
            path: element.path,
            name: element.name,
            title: element.title || element.meta.title,
          }
          arr.push(obj)
        });
        sessionStorage.setItem('breadcrumb', JSON.stringify(arr))
      }
      breadcrumbList.value = JSON.parse(sessionStorage.getItem('breadcrumb') || '[]')
    },{deep: true, immediate: true})
    return {
      breadcrumbList,
    }
  }
})
</script>
<style lang="scss" scoped>
.breadcrumb {
  flex-shrink: 0;
  width: 100%;
  padding: 10px;
  background: #f9fbff;
}
</style>
